/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.util;

import org.zhiqim.kernel.annotation.AnAlias;

/**
 * 线程相关工具类
 *
 * @version v1.0.0 @author zouzhigang 2014-2-27 新建与整理
 */
@AnAlias("Threads")
public class Threads
{
    /**
     * 获取调用者堆栈对象
     * 
     * @return  调用者堆栈
     */
    public static StackTraceElement getInvoker()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        return elems[3];//0是Thread本身，1是Threads，2是getInvoker方法的使用者，3才是正主，引入getInvoker使用的调用者
    }
    
    /**
     * 获取调用者类名、方法名和行数
     * 
     * @return  调用者堆栈字符串
     */
    public static String getInvokerString()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        StackTraceElement elem = elems[3];
        return new StringBuilder()
            .append("[").append(elem.getClassName()).append("]")
            .append("[").append(elem.getMethodName()).append("]")
            .append("[第").append(elem.getLineNumber()).append("行]")
            .toString();
    }
    
    /**
     * 获取调用者类名、方法名和行数简写
     * 
     * @return  调用者堆栈字符串
     */
    public static String getInvokerAbbr()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        StackTraceElement elem = elems[3];
        String className = Strings.removeLeftByLast(elem.getClassName(), ".");
        
        return new StringBuilder()
            .append("[")
            .append(className).append(".").append(elem.getMethodName())
            .append("(第").append(elem.getLineNumber()).append("行)")
            .append("]")
            .toString();
    }
    
    /***********************************************************************************/
    //中断线程
    /***********************************************************************************/
    
    /**
     * 忽略线程睡眠时的中断异常，使用时放置到while最下端
     * 
     * @param millis    毫秒数
     */
    public static void sleepIgnoreException(long millis)
    {
        if (millis <= 0)
            return;
        
        try{Thread.sleep(millis);}catch (InterruptedException e){}
    }
}
